package com.baitengsoft.patentservicemonitor.job.utils;

import com.baitengsoft.patentservicemonitor.job.entity.SysDataAuditEntity;
import com.baitengsoft.patentservicemonitor.job.service.SysDataAuditService;
import com.baitengsoft.patentservicemonitor.job.service.impl.SysDataAuditServiceImpl;
import com.google.gson.Gson;
import com.baitengsoft.patentservicemonitor.common.utils.SpringContextUtils;
import com.baitengsoft.patentservicemonitor.job.entity.ScheduleJobEntity;
import com.baitengsoft.patentservicemonitor.job.entity.ScheduleJobLogEntity;
import com.baitengsoft.patentservicemonitor.job.service.ScheduleJobLogService;
import org.apache.commons.lang.StringUtils;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.quartz.QuartzJobBean;

import javax.annotation.Resource;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;


/**
 * 定时任务
 *
 * @author KennyGu
 * @email 89335272@qq.com
 * @date 2016年11月30日 下午12:44:21
 */
public class ScheduleJob extends QuartzJobBean {
    private Logger logger = LoggerFactory.getLogger(getClass());
    private ExecutorService service = Executors.newSingleThreadExecutor();

    @Autowired
    private SysDataAuditService sysDataAuditService;



    @Override
    protected void executeInternal(JobExecutionContext context) throws JobExecutionException {
        String jsonJob = context.getMergedJobDataMap().getString(ScheduleJobEntity.JOB_PARAM_KEY);
        ScheduleJobEntity scheduleJob = new Gson().fromJson(jsonJob, ScheduleJobEntity.class);
        //获取spring bean
        ScheduleJobLogService scheduleJobLogService = (ScheduleJobLogService) SpringContextUtils.getBean("scheduleJobLogService");
        //数据库保存执行记录
        ScheduleJobLogEntity log = new ScheduleJobLogEntity();
        log.setJobId(scheduleJob.getID());
        log.setBeanName(scheduleJob.getBeanName());
        log.setMethodName(scheduleJob.getMethodName());
        log.setParams(scheduleJob.getParams());
        log.setCreateTime(new Date());

        //任务开始时间
        long startTime = System.currentTimeMillis();

        try {
            //执行任务
            logger.info("任务准备执行，任务ID：" + scheduleJob.getID());

            SysDataAuditEntity dataAuditEntity = sysDataAuditService.get(scheduleJob.getDataid());

            if (dataAuditEntity == null || dataAuditEntity.getPlatformId() == null || dataAuditEntity.getPlatformId() == 0) {
                throw new RuntimeException("缺少平台Id");
            }
            ScheduleRunnable task = new ScheduleRunnable(scheduleJob.getBeanName(),
                    scheduleJob.getMethodName(), scheduleJob.getParams(), dataAuditEntity.getPlatformId().toString());
            Future<?> future = service.submit(task);
            future.get();
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times);
            //任务状态    0：成功    1：失败
            log.setStatus(0);

            logger.info("任务执行完毕，任务ID：" + scheduleJob.getID() + "  总共耗时：" + times + "毫秒");
        } catch (Exception e) {
            logger.error("任务执行失败，任务ID：" + scheduleJob.getID(), e);
            //任务执行总时长
            long times = System.currentTimeMillis() - startTime;
            log.setTimes((int) times);
            //任务状态    0：成功    1：失败
            log.setStatus(1);
            log.setError(StringUtils.substring(ExceptionUtils.getExceptionDetail(e), 0, 2000));
        } finally {
            scheduleJobLogService.save(log);
        }
    }
}
